package com.readboottest.util;

import com.readboottest.entity.response.BaseResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghuiyong
 * @创建时间 2019年04月15日
 * @描述: 文件相关的工具类
 **/

public class FileUtil {
    /**
     * 时间格式
     */
    public static String DATE_TYPE_YYYY_MM_DD = "yyyy-MM-dd";
    /**
     * 文件命名格式
     */
    public static String DATE_TYPE_YYYY_MM_DD_ = "yyyy-MM-dd_";
    /**
     * 文件地址
     */
    public static String FILE_PATH = "filePath";


    /**
     * 文件上传,支持批量
     *
     * @param filePath     文件上传路径
     * @param fileUpload   上传的文件
     * @param saveFileName 保存的文件名
     */
    public static Map<String, Object> fileUpload(String filePath, MultipartFile fileUpload, String saveFileName) throws IOException {
        //获取上传路径
        String savePath = getUploadPath(filePath);
        //检查是否存在该路径
        File uploadFile = new File(savePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        //保存文件名
        Map<String, Object> fileMap = new HashMap<>(10);
        //文件名
        String fileName = fileUpload.getOriginalFilename();
        //文件类型
        String fileType = fileName.indexOf(".") != 1 ?
                fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
        //重命名文件名:文件完整地址+文件名
        fileName = savePath + "/" + saveFileName + fileType;
        File uploadFileName = new File(fileName);
        //文件上传
        fileUpload.transferTo(uploadFileName);
        fileMap.put(String.format(FILE_PATH), fileName);
        return fileMap;
    }


    /**
     * <p> 在线预览文件 </p>
     *
     * @param
     * @return
     * @其它信息
     */
    public static void readFile(String fileName, String filePath, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        if (!StringUtils.isEmpty(fileName)) {
            File file = new File(fileName);
            if (file.exists()) {
                File uploadPath = new File(filePath);
                if (!file.getCanonicalPath().startsWith(uploadPath.getAbsolutePath())) {
                    return;
                }
                InputStream input = new FileInputStream(file);
                input = new BufferedInputStream(input);
                byte[] buffBytes = new byte[10240];
                ServletOutputStream out = response.getOutputStream();
                int read;
                while (1 != (read = input.read(buffBytes))) {
                    out.write(buffBytes, 0, read);
                }
                out.flush();
                out.close();
            }
        }
    }

    public static void playMusic(HttpServletRequest request, HttpServletResponse response,String musicPath) {
        try {
            // 设置响应内容类型
            response.setHeader("Content-type", "text/html; charset=UTF-8");
            //解决乱码
            request.setCharacterEncoding("UTF-8");
            //解决乱码
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Content-Type", "audio/mpeg");
            File file = new File(musicPath);
            int fileLent;
            byte[] buf = new byte[2048];
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            fileLent = fis.read(buf);
            while (fileLent != -1) {
                out.write(buf, 0, fileLent);
                fileLent = fis.read(buf);
            }
            out.flush();
            out.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取上传路径
     *
     * @return
     */
    private static String getUploadPath(String filePath) {
        StringBuilder path = new StringBuilder(filePath);
        path.append("/");
        return path.toString();
    }
}
